package com.archstoday.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.archstoday.BaseApp;
import com.archstoday.R;
import com.archstoday.adapter.SearchAdapter;
import com.archstoday.common.AsRes;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.SearchEntity;
import com.archstoday.utils.ToolUtils;
import com.base.http.common.BaseHttpClient;
import com.base.utils.MySharedPreferencesMgr;
import com.base.utils.StringUtil;
import com.xw.repo.refresh.PullToRefreshLayout;
import com.xw.repo.refresh.PullListView;

import java.util.ArrayList;
import java.util.List;

/**
 * 搜索结果页面
 */
public class SearchDetailsActivity extends AsScrollBaseActivity implements PullToRefreshLayout.OnRefreshListener {

    private EditText mSearchEdit;
    private PullToRefreshLayout mPullLayout;
    private PullListView mPullList;
    private LinearLayout mNoneLayout;
    private String mSearchStr;

    private SearchAdapter mAdapter;
    private int page;
    private List<String> mSearchHistory;
    private View mFootView;

    @Override
    protected void initView(Bundle bundle) {
        setContentView(R.layout.activity_search_details);
        mSearchEdit = (EditText) findViewById(R.id.search_edit);
        mPullLayout = (PullToRefreshLayout) findViewById(R.id.search_pull_layout);
        mPullList = (PullListView) findViewById(R.id.search_pull_list);
        mPullLayout.setOnRefreshListener(this);
        mNoneLayout = (LinearLayout) findViewById(R.id.search_none_layout);
    }

    @Override
    protected void initData(Bundle bundle) {
        mFootView = LayoutInflater.from(mContext).inflate(R.layout.view_load_more, null);
        mAdapter = new SearchAdapter(mContext);
        mPullList.setAdapter(mAdapter);
        mSearchHistory = MySharedPreferencesMgr.getList(SpfUtils.SEARCH_HISTORY);
        mSearchStr = getIntent().getStringExtra("search");
        mSearchEdit.setText(mSearchStr);
        page = 1;
        getData(mSearchStr);
    }

    @Override
    protected void initListener() {
        setOnClickListener(R.id.search_cancel_btn);

        mSearchEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    mSearchStr = textView.getText().toString();
                    if (!StringUtil.isEmpty(mSearchStr)) {
                        if (mSearchHistory != null) {
                            mSearchHistory.add(mSearchStr);
                        } else {
                            mSearchHistory = new ArrayList<>();
                            mSearchHistory.add(mSearchStr);
                        }
                        if (mSearchHistory.size() > 20) {
                            mSearchHistory.remove(0);
                        }
                        MySharedPreferencesMgr.setList(SpfUtils.SEARCH_HISTORY, mSearchHistory);

                        page = 1;
                        getData(mSearchStr);
                    }
                }
                return false;
            }
        });

        mPullList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (mAdapter.getItem(i) != null) {
                    if (StringUtil.equest(mAdapter.getItem(i).getCategoryId1(), "3")) {
                        getEvent(mApp.E_SEARCH, mApp.PAGE_TYPE_EG);
                        Intent intent = new Intent(mContext, NewDetailsActivity.class);
                        intent.putExtra("id", mAdapter.getItem(i).getArticleId());
                        startActivity(intent);
                    } else {
                        getEvent(mApp.E_SEARCH, mApp.PAGE_TYPE_TENDER);
                        Intent intent = new Intent(mContext, TenderDetailsActivity.class);
                        intent.putExtra("id", mAdapter.getItem(i).getArticleId());
                        startActivity(intent);
                    }
                }
            }
        });
    }

    @Override
    public void treatClickEvent(int id) {
        switch (id) {
            case R.id.search_cancel_btn:
                getEvent(BaseApp.E_CANCEL_SEARCH, BaseApp.PAGE_TYPE_CANCEL_SEARCH);
                appFinish();
                break;
        }
    }

    private void getData(String keyValue) {
        initParameter();
        mParams.put("source", "archsall");
        mParams.put("keyword", keyValue);
        mParams.put("categoryLevel", 1);
//        mParams.put("categoryId", );
        if (!StringUtil.isEmpty(MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""))) {
            mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        }
        mParams.put("plat", "android");
        mParams.put("ifa", mApp.getDeviceID(mContext));
        mParams.put("page", page);
        mParams.put("pageSize", 10);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.SEARCH),
                AsRes.SEARCH, mParams, SearchEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        mPullLayout.refreshFinish(true);
        mPullLayout.loadMoreFinish(true);
        if (client.getUrlIdentifier() == AsRes.SEARCH) {
            SearchEntity entity = (SearchEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                mAdapter.setTokens(mSearchStr);
                if (entity.getData().getDocs() != null && entity.getData().getDocs().size() > 0) {
                    mNoneLayout.setVisibility(View.GONE);
                    if (page == 1) {
                        mAdapter.setData(entity.getData().getDocs());
                    } else {
                        mAdapter.addData(entity.getData().getDocs());
                    }
                    page++;
                } else {
                    if (page == 1) {
                        mNoneLayout.setVisibility(View.VISIBLE);
                    } else {
                        mPullList.addFooterView(mFootView);
                        mPullList.setPullUpEnable(false);
                    }
                }
            }
        }
    }

    @Override
    protected void onError(Throwable error, BaseHttpClient client) {
        try {
            mPullLayout.refreshFinish(true);
            mPullLayout.loadMoreFinish(true);

            mNoneLayout.setVisibility(View.VISIBLE);
            mPullList.setPullUpEnable(false);
        } catch (Exception e) {

        }

        new Thread() {
            @Override
            public void run() {
                new Handler(Looper.getMainLooper()).post(runnable);
            }
        }.start();
    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        mPullList.setPullUpEnable(true);
        mPullList.removeFooterView(mFootView);
        page = 1;
        getData(mSearchStr);
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        getData(mSearchStr);
    }
}